//
//  TableV.m
//  
//  jhf
//
//  Created by 计海峰 on 2020/3/29.
//  Copyright © 2020 计海峰. All rights reserved.
//

#import "TableV.h"
#import <MJRefresh/MJRefresh.h>
#import <CooperSDK/CooperSDK.h>

@interface TableV ()<UIGestureRecognizerDelegate>

@property (nonatomic, strong, readwrite) Class vmClass;

@property (nonatomic, strong, readwrite) id model;

@end

@implementation TableV

// 配置keys和values
- (void)configKeys:(NSArray <NSString *> *)keys values:(NSArray *)values; {
    _keys = keys;
    _values = values;
    [self keysValuesSetter];
}

// 设置keys values
- (void)keysValuesSetter {
    // 我的key
    if (self.keys && [self.keys isKindOfClass:[NSArray class]]) {
        if (self.keys.count > 0 && self.values && self.keys.count == self.values.count) {
            NSArray *properties = self.vm.j_getAllProperties;
            [self.keys enumerateObjectsUsingBlock:^(NSString * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                if ([properties containsObject:obj]) {
                    [self.vm setValue:[self.values objectAtIndex:idx] forKey:obj];
                }else {
                    NSLog(@"❤️❤️❤️❤️❤️❤️❤️❤️❤️❤️❤️%@属性不存在", obj);
                }
            }];
        }else {
            NSLog(@"❤️❤️❤️❤️❤️❤️❤️❤️❤️❤️❤️keys 或者 values 传参不正确");
        }
        [self.vm configDown];
    }
    // 固定row
    [self.vm forRows];
    // 获取数据
    [self.vm refreshData:nil];
}

// MARK:- 绑定
- (void)bindModel {
    // 绑定信号
    @weakify(self)
    [self.vm.signal subscribeNext:^(id  _Nullable x) {
        @strongify(self)
        if ([TABLE_DEFAULT_RELOAD_SIGNAL isEqualToString:x]) {
//            [self reloadData];
            [self.delayReloadSubject sendNext:@(++self.reloadCount)];
        }
    }];
    
    // 检查footer
    self.estimatedRowHeight = 44.f;
    [self.vm.checkFooterSignal subscribeNext:^(id  _Nullable x) {
        @strongify(self)
        if (self.enablePush) {
            [self.vm checkFooter:self result:x pagesize:self.pagesize];
        }
    }];
    
    // 绑定信号 rows
    [[self.vm.rows changeSignal] subscribeNext:^(id  _Nullable x) {
        @strongify(self)
//        [self reloadData];
        [self.delayReloadSubject sendNext:@(++self.reloadCount)];
    }];
    
    // 绑定信号 sections
    [[self.vm.sections changeSignal] subscribeNext:^(id  _Nullable x) {
        @strongify(self)
//        [self reloadData];
        [self.delayReloadSubject sendNext:@(++self.reloadCount)];
    }];
    
    [[[[self.delayReloadSubject distinctUntilChanged] filter:^BOOL(id  _Nullable value) {
        @strongify(self)
        self.isRefreshIng = true;
        return true;
    }] throttle:self.throttleTime] subscribeNext:^(id  _Nullable x) {
        @strongify(self)
        MAIN(^{
           [UIView performWithoutAnimation:^{
               [self reloadData];
           }];
       });
        self.isRefreshIng = false;
    }];
    
    
//    [[[self.delayReloadSubject distinctUntilChanged] throttle:0.2] subscribeNext:^(id  _Nullable x) {
//        @strongify(self)
//        MAIN(^{
//           [UIView performWithoutAnimation:^{
//               [self reloadData];
//           }];
//       });
//    }];
    
    // 绑定长按
    if (self.enableLongPress) {
        [self.vm configLongPress:self completion:^(NSIndexPath * _Nullable indexPath, UIGestureRecognizerState state) { }];
    }
    
    // 下拉
    [[RACObserve(self, enablePull) distinctUntilChanged] subscribeNext:^(id  _Nullable x) {
        @strongify(self)
        if (x && [x boolValue]) {
            self.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
                @strongify(self)
                [self.vm refreshData:^(id _Nonnull result) {
                    @strongify(self)
                    [self.mj_header endRefreshing];
                }];
            }];
        }else {
            self.mj_header = nil;
        }
    }];
}


// MARK:- 配置tableview
- (void)configTableview {
    
    @weakify(self);
    
    // 空白点击手机键盘
    if (self.enableTapEmpty) {
        UITapGestureRecognizer *gestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hiddeKeyboard:)];
        gestureRecognizer.delegate = self;
        gestureRecognizer.numberOfTapsRequired = 1;
        [self addGestureRecognizer:gestureRecognizer];
    }
    // 预计高度
    self.estimatedRowHeight = 44.f;
    if (@available(iOS 11.0, *)) {
        self.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    if (@available(iOS 15.0, *)) {
        self.sectionHeaderTopPadding = 0;
    }
    // tableview 代理绑定
    self
    .configRun
    .sectionsCount(^NSInteger{
        @strongify(self)
        return [self.vm sectionsCount];
    })
    .rowsAction(^NSArray<UITableViewRowAction *> * _Nullable(NSIndexPath * _Nonnull indexPath, UITableView * _Nonnull tableView) {
        @strongify(self)
        return [self.vm rowActionIndexPath:indexPath tableView:tableView];
    })
    .emptyDataConfig(^CPEmptyDataConfig * _Nullable{
        @strongify(self)
        return self.enableEmptyConifg ? (self.emptyConifg ? self.emptyConifg : [CPEmptyDataConfig initWithTitle:@"暂无数据" imageName:@""]) : nil;
    })
    .didScroll(^(UIScrollView * _Nonnull scrollView) {
        @strongify(self)
        if (self.enableTapEmpty) {
            [self cancelKeyboard];
        }
    })
    .sectionHeaderView(^UIView * _Nullable(NSInteger section, UITableView * _Nonnull tableView) {
        @strongify(self)
        return [self.vm sectionHeaderView:section tableView:tableView];
    })
    .sectionHeaderHeight(^CGFloat(NSInteger section, UITableView * _Nonnull tableView) {
        @strongify(self)
        return [self.vm sectionHeaderHeight:section tableView:tableView];
    })
    .sectionFooterView(^UIView * _Nullable(NSInteger section, UITableView * _Nonnull tableView) {
        @strongify(self)
        return [self.vm sectionFooterView:section tableView:tableView];
    })
    .sectionFooterHeight(^CGFloat(NSInteger section, UITableView * _Nonnull tableView) {
        @strongify(self)
        return [self.vm sectionFooterHeight:section tableView:tableView];
    })
    .selectSectionIndexTitles(^NSInteger(UITableView * _Nonnull tableView, NSString * _Nonnull title, NSInteger index) {
        @strongify(self)
        return [self.vm selectSectionIndexTitles:tableView title:title index:index];
    })
    .sectionIndexTitles(^NSArray<NSString *> * _Nullable(UITableView * _Nonnull tableView) {
        @strongify(self)
        return [self.vm sectionIndexTitles:tableView];
    })
    .cellCount(^NSInteger(NSInteger section, UITableView * _Nonnull tableView) {
        @strongify(self)
        return [self.vm sectionCellCount:section tableView:tableView];
    })
    .cellHeight(^CGFloat(NSIndexPath * _Nonnull indexPath, UITableView * _Nonnull tableView) {
        @strongify(self)
        return [self.vm cellHeight:indexPath tableView:tableView];
    })
    .cell(^UITableViewCell * _Nullable(NSIndexPath * _Nonnull indexPath, UITableView * _Nonnull tableView) {
        @strongify(self)
        return [self.vm cell:indexPath tableView:tableView];
    })
    .select(^(NSIndexPath * _Nonnull indexPath, UITableView * _Nonnull tableView) {
        @strongify(self)
        return [self.vm select:indexPath tableView:tableView];
    })
    .willDisplayCell(^(NSIndexPath * _Nonnull indexPath, UITableView * _Nonnull tableView, UITableViewCell * _Nonnull cell) {
        @strongify(self)
        return [self.vm willDisplayCell:indexPath tableView:tableView cell:cell];
    })
    .didScroll(^(UIScrollView * _Nonnull scrollView) {
        @strongify(self)
        if (self.enableTapEmpty) {
            [self cancelKeyboard];
        }
        return [self.vm didScroll:scrollView];
    })
    ;
    [self startRun];
    self.backgroundColor = [UIColor clearColor];
    
    // 固定row
    [self.vm forRows];
    // 获取数据
    [self.vm refreshData:nil];
}

- (void)hiddeKeyboard:(UIGestureRecognizer *)recognizer {
    [self cancelKeyboard];
}

- (void)cancelKeyboard {
    [self endEditing:true];
}


- (void)addActionObserver {
    NSLog(@"%@", self.bindKey);
    @weakify(self);
    [[[NSNotificationCenter defaultCenter] rac_addObserverForName:self.bindKey object:nil] subscribeNext:^(NSNotification * _Nullable x) {
        ActionModel *action = (ActionModel *)x.object;
        @strongify(self);
        if ([action runTarget:self.vm]) {
            return;
        }
        if ([action runTarget:self]) {
            return;
        }
    }];
}


// MARK:- class初始化
+ (instancetype)vWithClassStr:(NSString *)clsStr {
    return [[self alloc] initWithClass:NSClassFromString(clsStr) model:nil];
}

+ (instancetype)vWithClassStr:(NSString *)clsStr model:(id)model {
    return [[self alloc] initWithClass:NSClassFromString(clsStr) model:model];
}

+ (instancetype)vWithClass:(Class)cls {
    return [[self alloc] initWithClass:cls model:nil];
}

+ (instancetype)vWithClass:(Class)cls model:(id)model {
    return [[self alloc] initWithClass:cls model:model];
}

- (instancetype)initWithClass:(Class)cls model:(id)model {
    if (self = [super init]) {
        NSString *className = [NSString stringWithFormat:@"%@_%@", NSStringFromClass(self.class), NSStringFromClass(cls)];
        NSString *key = [NSString stringWithFormat:@"%@_%f_%u", className, NSDate.new.timeIntervalSince1970, arc4random()];
        self.bindKey = key;
        self.vmClass = cls;
        self.model = model;
        self.vm.bindKey = key;
        self.enableEmptyConifg = true;
        [self configTableview];
        [self bindModel];
        [self.vm initDown];
        [self addActionObserver];
        //
        if (jBaseSDK.jSignDebugModel) {
            NSLog(@"VM --> %@", NSStringFromClass(cls));
        }
    }
    return self;
}


- (TableVCVM *)vm {
    if (!_vm) {
        _vm = [[self.vmClass alloc] init];
    }
    return _vm;
}

- (RACSubject *)delayReloadSubject {
    if (!_delayReloadSubject) {
        _delayReloadSubject = [RACSubject subject];
    }
    return _delayReloadSubject;
}

@end
